<?php
namespace Modules\User\Http\Controllers\Client\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Modules\User\Entities\User;

use Modules\Core\Helpers\HttpClient;

use Validator;
use ThrowException;
use Auth;
use DB;
use Cache;
use Setting;
use Alipay;
use SMS;

// App上使用的登陆
class AlipayController extends Controller
{
    // App上使用
    public function loginWithMiniapp(Request $req)
    {
        $rule = [
            // 'iv' => ['required'],
            // 'encrypt_data' => ['required'],
            // 'code' => ['required'],
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        // 手机号简单验证
        if ($req->input('phone')) {
            if (strlen($req->phone) !== 11) {
                ThrowException::Conflict('手机号格式不正确~');
            }
        }

        // 如果有data_uuid，则直接从缓存中读取而不使用授权信息读取
        if ($req->input('data_uuid')) {
            $data = Cache::get('login_data_' . $req->data_uuid);
        }
        else {
            $data = Alipay::get()->getUserInfo($req->code);
            \Log::error($data);
        }

        // 有手机号则验证手机号
        if ($req->input('phone')) {
            SMS::verifyCode($req->phone, $req->phone_code, 'login') || ThrowException::Conflict('验证码不正确');
            $data['phone'] = $req->phone;
        }

        DB::beginTransaction();

        $openidType = 'miniapp';

        list($user, $isCreated) = User::findOrCreateByAlipay($data, Auth::clientName(), $openidType);

        // 没有找到用户并且没有创建新用户
        if (!$user) {

            $dataUuid = uniqid();
            Cache::put('login_data_' . $dataUuid, $data, 300);

            return [
                'data_uuid' => $dataUuid,
                'is_need_phone_number' => 1
            ];
        } 

        // 绑定邀请人
        if ($req->input('inviter') && $isCreated) {
            $inviter = User::getEntity([
                'uuid' => $req->inviter
            ], false);

            $user->bindInviter($inviter);
        }

        DB::commit();

        $token = Auth::generateToken($user);

        return [
            'token' => $token,
            'is_first_login' => $isCreated ? 1 : 0
        ];
    }

}
